#!/usr/bin/env python
# coding=utf-8

import pprint
import json
import re
import requests
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from utils.custom_log import log_start
logger = log_start('CMDB_API')

class CMDBInterface(object):
    def __init__(self, conndict,jobname):
        self.username = conndict["username"]
        self.password = conndict["password"]
        self.cmdbAPI = conndict["cmdbAPI"]
        self.appClusterName = jobname
    
    def getAppClusterInfo(self):
        headers = {
            'Authorization': 'Bearer {}'.format(self.get_token()),
            }
        cluster_url = '{0}/api/app/applications/?&search={1}'.format(self.cmdbAPI,self.appClusterName)
        ret =  requests.get(url=cluster_url,headers=headers ) 
        if ret.status_code == 200:
            pprint.pprint(ret.json()['data']['results'])
            return ret.json()['data']['results']


    def get_token(self):
        data= {
            'username': self.username, 
            'password': self.password
        }
        
        try:

            ret = requests.post(f'{self.cmdbAPI}/api/oauth/login/', json=data)
            if ret.status_code == 200 and 'token' in ret.json()['data']:
                token = ret.json()['data']['token']
            else:
                token = False
            return token
          
        except BaseException as e:
            error_msg = 'Get CMDB Token Failed:{}'.format(str(e))
            logger.error(error_msg)
            raise ValueError(error_msg)

if __name__ == '__main__':
    # 统一将主程序变量和测试代码放在此处
    conndict =  {
                'username': 'operator',
                'password': 'cmdb@123',
                'cmdbAPI': 'http://cmdb.pod.opsbase.cn'
            }
    cmdbAPI = CMDBInterface(conndict,'Pro.GM.zsj.web-game')
    ret = cmdbAPI.getAppClusterInfo()
    print(ret)